package com.koron.css2.newProjectCenter.callback;

import com.koron.css2.clientCenter.bean.*;
import com.koron.css2.clientCenter.mapper.*;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjMeterQuery;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.serviceManage.bean.UserDiscountBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.bean.UserMixtureBean;
import com.koron.css2.serviceManage.mapper.UserDiscountMapper;
import com.koron.css2.serviceManage.mapper.UserMixtureMapper;
import com.koron.css2.serviceManage.queryBean.UserMixtureQueryBean;
import com.koron.util.Constant;
import com.koron.util.Tools;
import com.koron.util.secret.RequestBean;
import com.koron.util.secret.SecretReqUtil;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工程报装-立户子节点
 * 立户审批通过之后，添加相应的信息
 *
 * @author 朱超
 * @since 2022-02-07
 */
public class RegisterAccountCallback extends AbstractProcessInterface {

    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, String toNodeCode) {
        try {
            if ("registerAccountApproval".equals(fromNodeCode) && "Process-end0".equals(toNodeCode)) {
                PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
                CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
                AccountInfoMapper accountInfoMapper = factory.getMapper(AccountInfoMapper.class);
                UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
                MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
                ChangeUserMapper changeUserMapper = factory.getMapper(ChangeUserMapper.class);
                List<UserPersonDetailBean> userPersonDetailBeanList = new ArrayList<>();
                UserMixtureMapper userMixtureMapper = factory.getMapper(UserMixtureMapper.class);
                UserDiscountMapper userDiscountMapper = factory.getMapper(UserDiscountMapper.class);
                UserPersonDetailMapper userPersonDetailMapper = factory.getMapper(UserPersonDetailMapper.class);

                // 1. 查出所有的立户所需信息
                PjMeterQuery pjMeterQuery = new PjMeterQuery();
                pjMeterQuery.setConsultId(billId);
                List<PjMeter> pjMeterList = pjMeterMapper.getList(pjMeterQuery);
                for (PjMeter pjMeter:pjMeterList) {
                    // 2. 先查出临时数据
                    CtmInfoBean ctmInfoTemp = ctmInfoMapper.getCtmInfoById(pjMeter.getUserCtmTempId(),CtmInfoBean.CTMTEMP);
                    AccountInfoBean accountInfoTemp = accountInfoMapper.getAccountInfoById(pjMeter.getUserAccountTempId(),AccountInfoBean.ACCOUNTTEMP);
                    UserBean userBeanTemp = userInfoMapper.getUserInfoById(pjMeter.getUserInfoTempId(), UserBean.USERTEMP);
                    // 3. 检查正式表中客户是否已存在，不存在则生成
                    CtmInfoBean ctmInfo = ctmInfoMapper.getCtmInfoByCtmNo(ctmInfoTemp.getCtmNo(),CtmInfoBean.CTM);
                    if (ctmInfo == null) {
                        ctmInfo.setCreateInfo(userInfo);
                        ctmInfoMapper.ctmInfoAdd(ctmInfo,CtmInfoBean.CTM);
                    }
                    // 4. 检查正式表中账户是否已存在，不存在则生成
                    AccountInfoBean accountInfo = accountInfoMapper.getAccountInfoByCode(accountInfoTemp.getAccountNo(), AccountInfoBean.ACCOUNT);
                    if (accountInfo == null) {
                        accountInfo.setCreateInfo(userInfo);
                        accountInfoMapper.accountInfoAdd(accountInfo,AccountInfoBean.ACCOUNT);
                    }
                    // 5. 更新用户临时表的客户和账户信息
                    userBeanTemp.setCtmNo(ctmInfo.getCtmNo());
                    userBeanTemp.setAccountNo(accountInfo.getAccountNo());
                    userInfoMapper.userInfoUpdate(userBeanTemp,UserBean.USERTEMP);
                    // 6. 用户正式表中新增数据
                    userBeanTemp.setCreateInfo(userInfo);
                    userInfoMapper.userInfoAdd(userBeanTemp,UserBean.USER);
                    // 7. 更新水表状态，用户编号
                    if (userBeanTemp.getMeterType().equals("1")) {
                        msInfoMapper.updateMsInfoStatus(userBeanTemp.getMeterNo(),2);
                        msInfoMapper.updateMsInfoUserNo(userBeanTemp.getMeterNo(), userBeanTemp.getUserNo());
                    }
                    // 8. 添加三户关联信息
                    userInfoMapper.userRelationHstAdd(Tools.getObjectId(), userBeanTemp.getCtmNo(), userBeanTemp.getUserNo(), userBeanTemp.getAccountNo());
                    // 9. 更新用水人口到UserPersonDetail,循环结束后批量
                    List<UserChangePersonBean> userChangePersonBeanList = changeUserMapper.getUserChangePersonById(pjMeter.getConsultId());
                    for (UserChangePersonBean userChangePersonBean: userChangePersonBeanList) {
                        UserPersonDetailBean bean = new UserPersonDetailBean();
                        bean.setCreateInfo(userInfo);
                        bean.setUserNo(userBeanTemp.getUserNo());
                        bean.setCertNo(userChangePersonBean.getCertNo());
                        bean.setCertType(userChangePersonBean.getCertType());
                        bean.setName(userChangePersonBean.getName());
                        bean.setLinkTel(userChangePersonBean.getLinkTel());
                        bean.setComments(userChangePersonBean.getComments());
                        userPersonDetailBeanList.add(bean);
                    }
                    // 10. 更新混合用水 (照抄的开户,OpenUserWorkFlow) TODO: 搞明白开户的对应逻辑
                    UserMixtureQueryBean userMixtureQueryBean = new UserMixtureQueryBean();
                    userMixtureQueryBean.setUserNo(userBeanTemp.getUserNo());
                    List<UserMixtureBean> userMixtureBeanList = userMixtureMapper.listTemp(userMixtureQueryBean);
                    if (userMixtureBeanList != null && userMixtureBeanList.size() > 0) {
                        List<UserMixtureBean> exists = userMixtureMapper.list(userMixtureQueryBean);
                        List<UserMixtureBean> mixtureBeans = new ArrayList<UserMixtureBean>();
                        mixtureBeans.addAll(exists);
                        for(UserMixtureBean userMixtureBean:userMixtureBeanList) {
                            int isExits = 0;
                            for(UserMixtureBean exist:exists) {
                                // 不明白这个加这个判断的原因
                                if(exist.getUseWaterType().equals(userMixtureBean.getUseWaterType()) &&
                                        userMixtureBean.getCostNo().equals(exist.getCostNo())) {
                                    isExits = 1;
                                    userMixtureBean.setUpdateInfo(userInfo);
                                    userMixtureMapper.update(userMixtureBean);
                                    mixtureBeans.remove(exist);
                                }
                            }
                            if(isExits == 0) {
                                userMixtureBean.setCreateInfo(userInfo);
                                if(StringUtils.isEmpty(userMixtureBean.getUserNo()))
                                    userMixtureBean.setUserNo(userBeanTemp.getUserNo());
                                userMixtureMapper.insert(userMixtureBean);
                            }

                        }
                        for(UserMixtureBean mixtureBean :mixtureBeans) {
                            userMixtureMapper.delete(mixtureBean);
                        }
                        userMixtureMapper.deleteTempById(billId);
                    }
                    // 11. 更新费用折扣 (照抄的开户,OpenUserWorkFlow)
                    List<UserDiscountBean> discountBeanList = userDiscountMapper.listTemp(userMixtureQueryBean);
                    if (discountBeanList != null && discountBeanList.size() > 0) {
                        List<UserDiscountBean> existslist = userDiscountMapper.list(userMixtureQueryBean);
                        List<UserDiscountBean> discountBeans = new ArrayList<UserDiscountBean>();
                        discountBeans.addAll(existslist);
                        for(UserDiscountBean userDiscountBean:discountBeanList) {
                            int isExits = 0;
                            for(UserDiscountBean exist:existslist) {
                                // 不明白这个加这个判断的原因
                                if(exist.getCostId().equals(userDiscountBean.getCostId())) {
                                    isExits = 1;
                                    userDiscountBean.setUpdateInfo(userInfo);
                                    userDiscountMapper.update(userDiscountBean);
                                    discountBeans.remove(exist);
                                }
                            }
                            if(isExits == 0) {
                                userDiscountBean.setCreateInfo(userInfo);
                                if(StringUtils.isEmpty(userDiscountBean.getUserNo()))
                                    userDiscountBean.setUserNo(userBeanTemp.getUserNo());
                                userDiscountMapper.insert(userDiscountBean);
                            }

                        }
                        for(UserDiscountBean discountBean :discountBeans) {
                            userDiscountMapper.delete(discountBean);
                        }
                        userDiscountMapper.deleteTempById(billId);
                    }
                    // 12. 将数据同步到集抄系统
                    if("2".equals(userBeanTemp.getMeterType()) && userInfo.getCurWaterCode().length()==2) {
                        //银川系统传至集抄系统
                        logger.info("用户信息同步至集抄系统"+update("http://prod.yinchuanwater.com:9036/syncJc",userBeanTemp,ctmInfo.getCtmName()));
                    }
                }
                // 13. 新增UserPersonDetail数据
                if(userPersonDetailBeanList!=null && userPersonDetailBeanList.size()>0) {
                    userPersonDetailMapper.userPersonDetailAddList(userPersonDetailBeanList);
                }
                // 14. 返回结果
                return MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"工程报装-立户审批通过-数据添加成功",null);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("工程报装-立户审批通过-数据添加失败",e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL,"工程报装-立户审批通过-数据添加失败",null);
        }
    }

    private static String update(String url, UserBean bean,String name){
        //获取水表信息
        Map<String,Object> data=new HashMap<String,Object>();
        //获取表身码
        data.put("code", bean.getMeterNo());
        data.put("group", bean.getTenantId());
        data.put("usn", bean.getUserNo());
        data.put("areaId", bean.getClientContractAddr());
        data.put("installAddr", bean.getSetupMeterAddr());
        data.put("installTime", bean.getSetupMeterDate());
        data.put("position", bean.getSetupMeterLocation());
        data.put("name", name);
        data.put("concentrator", bean.getConcentratorNo());
        RequestBean reqBean = new RequestBean();
        reqBean.setUrl(url);
        reqBean.setData(data);
        String result = null;
        try {
            result = SecretReqUtil.sendToJc(reqBean,"updateMeter");

        }catch (Exception e){
            logger.error("调用集抄系统失败",e);
            return e+"";
        }
        return result;
    }


}
